package by.jabbby.ui.data;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import android.os.Parcel;
import by.jabbby.JabbbyException;
import by.jabbby.Logger;

public class DataParcibleUtil {
	
	

	public static void fillData(final Object obj, final Parcel out) {
		Class cl = obj.getClass();
		Field[] fields = cl.getFields();
		for (Field f : fields) {
			try {
				
				if ( Modifier.isTransient( f.getModifiers() ) ){
					continue;
				}
				
				String name = f.getName();
				String setter = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
				Method m = cl.getMethod(setter, f.getType());
				Object value = null;
				if(f.getType().equals(String.class)){
					value = out.readString();
				}else{
					if(f.getType().equals(int.class)){
						value = out.readInt();
					}else{
						if(f.getType().equals(long.class)){
							value = out.readLong();
						}else{
							JabbbyException je = new JabbbyException("DataParcibleUtil: Unsapport type"+ f.getType().toString());
							throw je;
						}
						
					}
				}
				
				m.invoke(obj, value);

			} catch (Exception e) {
				Logger.e(e);
			}

		}
	}

	public static void writeData(final Object obj, final Parcel in) {
		Class cl = obj.getClass();
		Field[] fields = cl.getFields();
		for (Field f : fields) {
			try {
				
				if ( Modifier.isTransient( f.getModifiers() ) ){
					continue;
				}
				
				String name = f.getName();
				String getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
				Method m = cl.getMethod(getter, f.getType());
				Object value = m.invoke(obj);
				if(f.getType().equals(String.class)){
					in.writeString((String)value);
				}else{
					if(f.getType().equals(int.class)){
						in.writeInt((Integer)value);
					}else{
						if(f.getType().equals(long.class)){
							in.writeLong((Long)value);
						}else{
							JabbbyException je = new JabbbyException("DataParcibleUtil: Unsapport type"+ f.getType().toString());
							throw je;
						}
						
					}
				}
				
				m.invoke(obj, value);

			} catch (Exception e) {
				Logger.e(e);
			}

		}

	}

}
